<template>
  <div>
    <!-- 添加弹框 -->
    <div>
      <a-button type="primary" @click="showModal" class="add"> 添加 </a-button>
      <a-modal
        title="添加用户"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form :form="form">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="账号"
          >
            <a-input v-model="addForm.surname" placeholder="请输入您的账号" />
          </a-form-item>
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="密码"
          >
            <a-input v-model="addForm.password" placeholder="请输入您的密码" />
          </a-form-item>
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="姓名"
          >
            <a-input v-model="addForm.name" placeholder="请输入您的姓名" />
          </a-form-item>
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="邮箱"
          >
            <a-input
              v-model="addForm.emailAddress"
              placeholder="请输入您的邮箱"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
    <!-- /添加弹框 -->
    <a-table :columns="columns" :data-source="data">
      <a slot="name" slot-scope="text">{{ text }}</a>
      <span slot="customTitle">姓名</span>
      <span slot="isActive" slot-scope="scope">
        <a-switch
          :default-checked="scope.isActive"
          @change="onChange(scope)"
          v-if="scope.id != 2"
        ></a-switch>
      </span>

      <span slot="action" slot-scope="scope">
        <a-space>
          <a-popconfirm
            title="是否确认删除"
            ok-text="Yes"
            cancel-text="No"
            @confirm="confirm"
            @cancel="cancel"
          >
            <a-button type="danger" @click="del(scope.id)" v-if="scope.id != 2">
              删除
            </a-button>
          </a-popconfirm>

          <a-button
            type="primary"
            @click="showModalDis(scope.id)"
            v-if="scope.id != 2"
          >
            编辑
          </a-button>
        </a-space>

        <a-modal
          title="编辑用户资料"
          :visible="visibleDis"
          :confirm-loading="confirmLoadingDis"
          @ok="handleOkDis"
          @cancel="handleCancelDis"
        >
          <a-form :form="form">
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="账号"
            >
              <a-input
                v-model="preservationData.surname"
                placeholder="请输入您的账号"
              />
            </a-form-item>

            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="姓名"
            >
              <a-input
                v-model="preservationData.name"
                placeholder="请输入您的姓名"
              />
            </a-form-item>
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="邮箱"
            >
              <a-input
                v-model="preservationData.emailAddress"
                placeholder="请输入您的邮箱"
              />
            </a-form-item>
          </a-form>
        </a-modal>
      </span>
    </a-table>
    <div>
      <a-pagination
        v-model="current"
        :page-size-options="pageSizeOptions"
        :total="total"
        show-size-changer
        :page-size="pageSize"
        @showSizeChange="onShowSizeChange"
        @change="getChange"
      >
        <template slot="buildOptionText" slot-scope="props">
          <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
          <span v-if="props.value === '50'">全部</span>
        </template>
      </a-pagination>
    </div>
  </div>
</template>

<script>
import {
  getUserData,
  AddUserData,
  DeltUser,
  displayState,
  getOneUser,
  displayUserData,
} from "../../../services/dataSource";
export default {
  name: "sss",
  components: {},
  props: {},
  data() {
    return {
      // 分页
      pageSizeOptions: ["10", "20", "30", "40", "50"],
      current: 1,
      pageSize: 10,
      total: null,
      // 删除的id
      delId: "",
      // 编辑用户的id
      userId: "",
      // 保存数据
      preservationData: {
        surname: "",
        name: "",
        emailAddress: "",
        creationTime: "",
      },
      // 添加数据
      addForm: {
        surname: "",
        name: "",
        emailAddress: "",
        password: "",
      },
      // 控制ipt和lable的大小
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
      },
      checkNick: false,
      form: this.$form.createForm(this, { name: "dynamic_rule" }),
      // 编辑弹框
      visibleDis: false,
      confirmLoadingDis: false,
      // 弹窗
      visible: false,
      confirmLoading: false,
      columns: [
        {
          dataIndex: "name",
          key: "name",
          align: "center",
          slots: { title: "customTitle" },
          scopedSlots: { customRender: "name" },
        },
        {
          title: "账号",
          dataIndex: "surname",
          key: "surname",
          align: "center",
        },
        {
          title: "邮箱",
          dataIndex: "emailAddress",
          key: "emailAddress",
          align: "center",
        },
        {
          title: "状态",
          // dataIndex: 'isActive',
          key: "isActive",
          align: "center",
          scopedSlots: { customRender: "isActive" },
        },

        {
          title: "操作",
          key: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      data: [],
    };
  },
  computed: {},
  watch: {},
  methods: {
    // 分页
    // 页数发生变化
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.getData();
    },
    // 页码值发生的变化
    getChange(pageNumber) {
      this.getData();
    },
    check() {
      this.form.validateFields((err) => {
        if (!err) {
          console.info("success");
        }
      });
    },
    handleChange(e) {
      this.checkNick = e.target.checked;
      this.$nextTick(() => {
        this.form.validateFields(["nickname"], { force: true });
      });
    },
    // 点击编辑按钮获取数据
    showModalDis(id) {
      this.userId = id;
      getOneUser(id)
        .then((res) => {
          this.preservationData.name = res.data.result.name;
          this.preservationData.emailAddress = res.data.result.emailAddress;
          this.preservationData.surname = res.data.result.surname;
          this.preservationData.creationTime = res.data.result.creationTime;
        })
        .catch((err) => {
          console.log(err);
        });
      this.visibleDis = true;
    },
    handleOkDis() {
      if (
        (this.preservationData.surname == "",
        this.preservationData.name == "",
        this.preservationData.emailAddress == "",
        this.preservationData.creationTime == "")
      ) {
        return this.$message.info("请填写完整");
      }

      displayUserData(
        this.userId,
        this.preservationData.name,
        this.preservationData.surname,
        this.preservationData.surname,
        this.preservationData.emailAddress,
        this.preservationData.creationTime,
        this.preservationData.creationTime
      )
        .then((res) => {
          this.getData();
        })
        .catch((err) => {
          console.log(err);
        });

      this.visibleDis = false;
    },
    handleCancelDis() {
      this.visibleDis = false;
    },

    showModal() {
      this.visible = true;
    },

    handleOk() {
      if (
        (this.addForm.surname == "",
        this.addForm.name == "",
        this.addForm.surname == "",
        this.addForm.emailAddress == "",
        this.addForm.password == "")
      ) {
        return this.$message.info("请输入完整内容");
      }
      // this.ModalText = 'The modal will be closed after two seconds';

      AddUserData(
        this.addForm.surname,
        this.addForm.name,
        this.addForm.surname,
        this.addForm.emailAddress,
        this.addForm.password
      )
        .then((res) => {
          this.getData();
          this.visible = false;
          this.addForm.surname = "";
          this.addForm.name = "";
          this.addForm.emailAddress = "";
          this.addForm.password = "";
        })
        .catch((err) => {
          return this.$message.info("添加失败");
        });
    },
    handleCancel(e) {
      this.visible = false;
      this.addForm.surname = "";
      this.addForm.name = "";
      this.addForm.emailAddress = "";
      this.addForm.password = "";
    },
    //  获取数据
    getData() {
      getUserData((this.current - 1) * this.pageSize, this.pageSize)
        .then((res) => {
          // console.log(res.data.result.items);
          for (let i = 0; i < res.data.result.items.length; i++) {
            res.data.result.items[i].key = i;
          }
          if (res.data.result.items.length == 0) {
            getUserData(0, this.pageSize)
              .then((res) => {
                for (let i = 0; i < res.data.result.items.length; i++) {
                  res.data.result.items[i].key = i;
                }
                this.total = res.data.result.totalCount;
                this.data = res.data.result.items;
              })
              .catch((err) => {
                console.log(err);
              });
          }
          this.total = res.data.result.totalCount;
          this.data = res.data.result.items;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 删除按钮
    del(id) {
      this.delId = id;
      // this.$message.success('删除成功');
    },
    confirm(e) {
      DeltUser(this.delId)
        .then((res) => {
          this.getData();
          this.$message.success("删除成功");
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 删除取消
    cancel() {
      this.$message.error("取消删除");
    },
    // 状态按钮
    onChange(scope) {
      if (scope.isActive == false) {
        displayState(true, scope.id).then((res) => {
          this.$message.info("修改成功");
          this.getData();
        });
      } else if (scope.isActive == true) {
        displayState(false, scope.id).then((res) => {
          this.$message.info("修改成功");
          this.getData();
        });
      }
    },
  },
  //声明周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getData();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
};
</script>

<style scoped>
.add {
  margin-bottom: 1.25rem;
}
</style>